import React, {useEffect, useRef, useState} from 'react';
import {
  Button,
  Checkbox,
  Form,
  GetRef,
  Input,
  Space,
  Table,
  TableColumnType,
} from 'antd';
import {ProjectData} from "@/pages/New/components/projectOverview/selfGeneratedDataConstant";
import {SearchOutlined} from "@ant-design/icons";

interface ProjectsDetail {
  key: string;
  // 在这里添加项目对象需要的5个属性
  name: string;
  age: string;
  task: string;
  address: string;
  description: ProjectsDetail[];
}

interface Item {
  key: string;
  serialNumber: number;
  projectNumber: string;
  name: string;
  creator: string;
  projectDetail: ProjectsDetail[]
}

// 定义类型
type Props = {
  selectedRowInvoke: any
}
type DataIndex = keyof Item;
type InputRef = GetRef<typeof Input>;

// 指定props参数的类型
const FindProjectTable: React.FC<Props> = (props: Props) => {
  // 相当于把findProject中的func函数传递给update
  const {selectedRowInvoke} = props;
  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState('');
  const [data, setData] = useState<Item[]>([]);
  const searchInput = useRef<InputRef>(null);

  // 初始化数据
  useEffect(() => {
    setData(ProjectData);
  }, []);

  const isEditing = (record: Item) => record.key === editingKey;

  const cancel = () => {
    setEditingKey('');
  };

  const edit = (record: Partial<Item> & { key: React.Key }) => {
    console.log(record);
    // 待修改
    form.setFieldsValue({serialNumber: '', projectNumber: '', name: '', creator: '', projectDetail: [], ...record});
    setEditingKey(record.key);
  };

  const save = async (key: React.Key) => {
    try {
      // 待修改
      const row = (await form.validateFields()) as Item;
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      console.log(row, index, key);
      if (index >= 0) {
        const item = newData[index];
        // 第三个参数是向数组添加的新对象
        // {...item, ...row} 用于合并两个对象的所有属性到一个新的对象中
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  // 定义一个React状态变量 selectedRowKeys，用于存储被选中的行的键值（通常是数据源中每一项的唯一标识符）。同时，通过 useState 钩子初始化为一个空数组
  const [selectedRowKey, setSelectedRowKey] = useState<React.Key | null>();

  // 定义处理行选中变化的回调函数
  // isChecked:表示当前Checkbox是否被选中; key:当前操作行的键值
  const handleRowSelectChange = (isChecked: boolean, key: React.Key) => {
    console.log(key, isChecked);
    if (isChecked) {
      // isChecked为true时，将key添加到selectedRowKeys数组中
      setSelectedRowKey(key);
      // 点击checkBox触发handleRowSelectChange函数，然后这里调用selectedRowInvoke函数，将选中行的项目详情数据传过去
      selectedRowInvoke(data[Number(key) - 1].projectDetail, key, isChecked);
    } else {
      // isChecked为false时，则从selectedRowKeys数组中移除对应的key
      setSelectedRowKey(null);
    }
  };

  const getColumnSearchProps = (dataIndex: DataIndex, description: string): TableColumnType<Item> => ({
    // 生成一个下拉过滤器
    /*
        setSelectedKeys: 用于设置当前选中的筛选项。
        selectedKeys: 当前选中的筛选项数组。
        confirm: 确认筛选操作的回调函数。
        clearFilters: 清除筛选条件的回调函数。
     */
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <form
        style={{padding: "1rem", display: "flex", gap: "0.5rem"}}
        onSubmit={(e) => {
          e.preventDefault();
          confirm();
        }}>
        <Input
          ref={searchInput}
          placeholder={description}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
        />
        <Space>
          {/*通过 setSelectedKeys 更新筛选项，并调用 confirm() 来应用筛选*/}
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          {/*清空筛选项、清除筛选条件并调用 confirm() 来刷新表格数据*/}
          <Button type="primary" htmlType="button" onClick={() => {
            setSelectedKeys([])
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            clearFilters && clearFilters();
            confirm();
          }}>
            重置
          </Button>
        </Space>
      </form>
    ),
    filterIcon: (filtered: boolean) => (
      <SearchOutlined style={{color: filtered ? '#1677ff' : undefined, fontSize: '1.4em'}}/>
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes((value as string).toLowerCase()),
    render: (text) => (text),
  });

  const columns = [
    {
      title: '选择',
      dataIndex: 'key',
      key: 'key',
      width: '7%',
      align: "center",
      render: (_: any, record: Item) => (
        <Checkbox
          checked={selectedRowKey === record.key}
          onChange={(e) => {
            handleRowSelectChange(e.target.checked, record.key);
          }}
        />
      ),
    },
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: '10%',
      align: "center",
      editable: true,
    },
    {
      title: '项目编号',
      dataIndex: 'projectNumber',
      key: 'projectNumber',
      width: '20%',
      align: "center",
      editable: true,
    },
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      width: '35%',
      align: "center",
      editable: true,
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
      width: '15%',
      align: "center",
      editable: true,
      ...getColumnSearchProps('creator', '请输入创建人名称')
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        inputType: col.dataIndex === 'serialNumber' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <Table
      bordered
      dataSource={data}
      columns={mergedColumns}
      rowClassName="editable-row"
      pagination={{
        onChange: cancel,
      }}
    />
  );
};

export default FindProjectTable;
